package vip.web3.api.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vip.web3.api.annotation.Login;
import vip.web3.api.dao.biz.*;
import vip.web3.api.entity.base.PlatformConfig;
import vip.web3.api.entity.biz.ProductEntity;
import vip.web3.api.form.user.OrderForm;
import vip.web3.api.service.base.PlatformConfigService;
import vip.web3.api.service.biz.*;
import vip.web3.common.utils.DateUtils;
import vip.web3.common.utils.R;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/home")
public class HomeApi {

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserWalletService userWalletService;

    @Autowired
    private RecordService recordService;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserWalletDao userWalletDao;

    @Autowired
    private RecordDao recordDao;

    @Autowired
    private OrderDao orderDao;
    @Resource
    private PlatformConfigService platformConfigService;

    @RequestMapping("/product/list")
    public R listProduct(HttpServletRequest request) {
        List<ProductEntity> list = productService.listProducts();
        return R.ok().put("data", list);
    }

    @Login
    @PostMapping("/order")
    public synchronized R order(@Valid @RequestBody OrderForm form) {

        // 要给别人一次性奖励(job)
        // 要激活自己用户状态
        // 第一次下单给自己钱包定type
        // 余额不够要先充值
        // 如果二次下单要用原来的钱包type
        // 改余额表
        // 首次购买1-8任何一款产品都送0号产品，投资累计收益累计，复购不送
        // 记录order表
        // 事务
        Date date = new Date();
        String format = DateUtils.format(date, DateUtils.DATE_PATTERN);
        int countOrder = orderDao.countOrder(format + " 00:00:00", format + " 23:59:59");
        if (countOrder > 300) {
            return R.error(-1, "暂时无法下单!");
        }
        orderService.order(form);
        return R.ok();
    }


    @GetMapping("/query/config")
    public R queryConfig() {
        return R.ok().put("data", platformConfigService.selectOne());
    }

    @GetMapping("/query/data")
    public R queryData() {
        return R.ok().put("data", platformConfigService.queryData());
    }




}
